﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WMM.Tapioca.Linkbase;
using System.Text.RegularExpressions;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;
using WMM.Tapioca.Utilities;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The precision filter can be used to match facts based on their having a minimum actual or inferred
    /// precision, noting that precision can be inferred from the value of the @decimal attribute. 
    /// </summary>
    public class PrecisionFilter : Filter
    {
        private int minimum;

        /// <returns> The value of the @minimum attribute on the precision filter.  </returns>
        public int Minimum
        {
            get { return minimum; }
            set { minimum = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public PrecisionFilter(Resource resource)
            : base(resource)
        {
            string expression = (string)resource.ResourceXElement.Attribute("minimum") ?? string.Empty;
            expression = expression.TrimEnd().TrimStart();
            expression = Regex.Replace(expression, @"\s+", " ");
            string value = EvaluateExpression(expression);

            Int32.TryParse(value, out minimum);
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            List<FactItem> itemListTemp = new List<FactItem>();

            foreach (FactItem item in itemsToFilter)
            {
                if (item.IsNilSpecified || !item.Concept.SchemaElement.ElementSchemaType.IsNumeric())
                {
                    continue;
                }

                if (Complement ? !(item.Precision >= Minimum) : item.Precision >= Minimum)
                {
                    itemListTemp.Add(item);
                }
            }

            return itemListTemp;
        }
    }
}
